/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.validate.validator;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.dspl.model.DataType;
import com.google.dspl.model.Table;
import com.google.dspl.model.Table.Column;
import com.google.dspl.model.Value;
import com.google.dspl.validate.ItemReference;
import com.google.dspl.validate.ValidationContext;
import com.google.dspl.validate.violation.ColumnConflictingConstantValueTypeViolation;
import com.google.dspl.validate.violation.ColumnNoTypeViolation;
import com.google.dspl.validate.violation.Violation;

import java.util.List;

/**
 * {@link Validator} for {@link Column}s.
 *
 * @author Maryla Ustarroz Calonge
 */
public class ColumnValidator implements Validator<Column> {

  private final Table table;

  public ColumnValidator(Table table) {
    this.table = table;
  }

  @Override
  public List<Violation> validate(Column column, ValidationContext context) {
    ItemReference itemReference =
        ItemReference.reference(context.getCurrentDataset(), table, column);

    Builder<Violation> violations = ImmutableList.builder();

    Value constantValue = column.getConstantValue();
    DataType type = column.getType();
    if (type == null) {
      violations.add(
          new ColumnNoTypeViolation(itemReference, column.getId(), table.getId()));
    } else if (constantValue != null) {
      if (!ValidationHelper.isValidValueOfType(constantValue, type)) {
        violations.add(new ColumnConflictingConstantValueTypeViolation(
            itemReference,
            column.getId(),
            table.getId(),
            constantValue,
            type));
      }
    }

    return violations.build();
  }
}
